/*
* 添加消费
* */

import 'dart:convert';

import 'package:center_beijing/api/authorization_api.dart';
import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/common/numLengthInputFormatter.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_input_widget.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_select_widget.dart';
import 'package:center_beijing/widgets/imageSelect_widget.dart';
import 'package:center_beijing/widgets/textarea_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'dart:io';

import 'package:images_picker/images_picker.dart';
import 'package:http_parser/http_parser.dart';
class AddConsumption extends StatefulWidget {
  @override
  _AddConsumptionState createState() => _AddConsumptionState();
}

class _AddConsumptionState extends State<AddConsumption> {
  CustomLoading loading = CustomLoading.withMessage('请稍候...');
  var score = TextEditingController();
  var currentId = Go.Get.arguments;
  List<SelectItems> shopList = []; //商店列表
  SelectItems selectShop = SelectItems();

  var currentPersonScore = Map();
  var remark = '';
  ImageForm.FormData formData;
  List photos = []; //购买人照片
  List commodity = []; //商品照片
  List passPhoto = [];

  @override
  void dispose() {
    loading.dismiss();
    // TODO: implement dispose
    super.dispose();
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getAllInfo();
  }

  getAllInfo() async {
    loading.show(delay: 15);
    Future.wait([this.getAllShop(), this.getScore()]).then((results) {
      List<SelectItems> tem = [];
      if (results[0] != null) {
        results[0].forEach((item) {
          tem.add(SelectItems(
              label: item['name'], value: item['id'].toString(), dict: item));
        });
      }
      if (results[1] != null) {
        currentPersonScore = results[1];
      }
      this.setState(() {
        shopList = tem;
      });
    }).whenComplete(() => loading.dismiss());
  }

  Future getScore() async {
    var pass = {'employeeId': currentId};
    var result = await getEmployeeScore(pass);
    return result;
  }

  Future getAllShop() async {
    var pass = {'projectSectionId': GlobalConfig.selectFactory.tag};
    var result = await getShops(pass);
    return result;
  }

  submit() async {
    var pass = {
      'item': json.encode({
        'projectSectionId': GlobalConfig.selectFactory.tag,
        'employeeId': currentId,
        'shopId': selectShop.value,
        'scores': "-${this.score.text}",
        'orderContent': remark,
        'posType': '10',
        'posName': 'APP',
        'personAttrId': passPhoto[0]['fileId'],
        'goodsAttrId': passPhoto[0]['fileId']
      })
    };
    var result = await saveEmployeeScoreExpense(pass);
    loading.dismiss();
    if (result != null) {
      Fluttertoast.showToast(msg: '兑换成功！');
      Go.Get.back();
    }
  }

  bool justify() {
    if (selectShop.value == null) {
      Fluttertoast.showToast(msg: '请选择商店');
      return false;
    } else if (this.score.text == '') {
      Fluttertoast.showToast(msg: '请输入扣除积分!');
      return false;
    } else if (double.parse(this.score.text) >
        (currentPersonScore['preScores']!=null?double.parse(currentPersonScore['preScores'].toString()):0)) {
      Fluttertoast.showToast(msg: '请输入积分不足！');
      return false;
    } else if (remark == '') {
      Fluttertoast.showToast(msg: '请输入消费内容!');
      return false;
    } else if (this.photos.length == 0) {
      Fluttertoast.showToast(msg: '请上传购买人照片!');
      return false;
    } else if (this.commodity.length == 0) {
      Fluttertoast.showToast(msg: '请上传商品照片!');
      return false;
    } else {
      return true;
    }
  }

  Future addImage() async {
    this.passPhoto = [];
    loading.show(delay: 30);
    if (this.photos.length > 0) {
      var temPhotos = [];
      temPhotos.addAll(this.photos);
      temPhotos.addAll(this.commodity);
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      for (int i = 0; i < temPhotos.length; i++) {
        Media asset = temPhotos[i];
        File file = File(asset.path);
        formData.files.add(MapEntry("files",
            await ImageForm.MultipartFile.fromFile(file.path.toString(),contentType: MediaType('image',file.path.toString().split('.').last))));
      }
      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        this.passPhoto = [];
        result.forEach((item) {
          this.passPhoto.add({
            'fileId': item['attachmentId'],
            'fileName': item['fileName'],
            'fileType': item['fileName'].split('.').last
          });
        });
        this.submit();
      }
    } else {
      this.submit();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('商家消费'),
        ),
        body: SafeArea(
          child: GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
            },
            child: Container(
              padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).padding.bottom + 60),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      color: Colors.white,
                      margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                      child: CustomSelectWidget(
                        enable: false,
                        rightArrow: false,
                        require: false,
                        rightText: currentPersonScore['preScores'] != null
                            ? currentPersonScore['preScores'].toString()
                            : '0',
                        title: '个人积分',
                      ),
                    ),
                    Container(
                      color: Colors.white,
                      margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                      child: CustomSelectWidget(
                        enable: true,
                        require: true,
                        rightText:
                            selectShop.label != null ? selectShop.label : '请选择',
                        items: shopList,
                        selectCallback: (value) => this.setState(() {
                          selectShop = value;
                        }),
                        title: '商店',
                      ),
                    ),
                    Container(
                      color: Colors.white,
                      margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                      padding: EdgeInsets.fromLTRB(
                          Styles.spacing8, 0, Styles.spacing8, 0),
                      child: CustomInput(
                        textAlign: TextAlign.right,
                        keyboardType:
                            TextInputType.numberWithOptions(decimal: true),
                        inputformat: [
                          LengthLimitingTextInputFormatter(10),
                          NumLengthInputFormatter(digit: 2),
                        ],
                        title: '扣除积分',
                        placeHold: '请输入',
                        textInput: this.score,
                        clearAll: false,
                        require: true,
                      ),
                    ),
                    Container(
                      color: Colors.white,
                      margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                      padding: EdgeInsets.fromLTRB(
                          Styles.spacing8, 0, Styles.spacing8, 0),
                      child: TextAreaWidget(
                        maxLength: 100,
                        labelText: '消费内容',
                        defaultValue: '',
                        placeholder: '请输入消费内容',
                        disabled: false,
                        required: true,
                        rows: 4,
                        onChange: (value) => this.setState(() {
                          remark = value;
                        }),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                      color: Colors.white,
                      child: Column(
                        children: [
                          Padding(
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing16, Styles.spacing8, 0, 0),
                            child: Row(
                              children: <Widget>[
                                Text(
                                  '*',
                                  style: TextStyle(
                                      color: Styles.RedColor,
                                      fontSize: Styles.MiddleFont17),
                                ),
                                Text(
                                  '购买人照片',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.MiddleFont17),
                                ),
                              ],
                            ),
                          ),
                          ImageSelectWidget(
                            maxNumber: 1,
                            onchange: (value) {
                              this.setState(() {
                                photos = value;
                              });
                            },
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                      color: Colors.white,
                      child: Column(
                        children: [
                          Padding(
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing16, Styles.spacing8, 0, 0),
                            child: Row(
                              children: <Widget>[
                                Text(
                                  '*',
                                  style: TextStyle(
                                      color: Styles.RedColor,
                                      fontSize: Styles.MiddleFont17),
                                ),
                                Text(
                                  '商品',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.MiddleFont17),
                                ),
                              ],
                            ),
                          ),
                          ImageSelectWidget(
                            maxNumber: 1,
                            onchange: (value) {
                              this.setState(() {
                                commodity = value;
                              });
                            },
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                if(this.justify()){
                  showDialog(
                      barrierDismissible: false,
                      context: this.context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text('注意'),
                          content: Text('确认提交吗？'),
                          actions: <Widget>[
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "取消",
                                  style: TextStyle(color: Colors.black),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ),
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "确定",
                                  style: TextStyle(color: Colors.red),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                  this.addImage();
                                },
                              ),
                            ),
                          ],
                        );
                      });
                }

              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '确定提交',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
